package org.joy.util;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

public class ObjectFactory {

	private static final Logger LOGGER = Logger.getLogger(ObjectFactory.class.getName());

	private static List<ClassLoader> externalClassLoaders;

	static {
		externalClassLoaders = new ArrayList<ClassLoader>();
	}

	private ObjectFactory() {
		super();
	}

	public static synchronized void addExternalClassLoader(ClassLoader classLoader) {
		ObjectFactory.externalClassLoaders.add(classLoader);
	}

	@SuppressWarnings("rawtypes")
	public static Class externalClassForName(String type) throws ClassNotFoundException {

		Class clazz;

		for (ClassLoader classLoader : externalClassLoaders) {
			try {
				classLoader.loadClass(type);
				clazz = Class.forName(type, true, classLoader);
				return clazz;
			} catch (ClassNotFoundException e) {
				LOGGER.info(e.getMessage());
			}
		}

		return internalClassForName(type);
	}

	public static Class<?> internalClassForName(String type) throws ClassNotFoundException {
		Class<?> clazz = null;

		try {
			ClassLoader cl = Thread.currentThread().getContextClassLoader();
			clazz = Class.forName(type, true, cl);
		} catch (ClassNotFoundException e) {
			LOGGER.info(e.getMessage());
		}

		if (clazz == null) {
			clazz = Class.forName(type, true, ObjectFactory.class.getClassLoader());
		}

		return clazz;
	}

	public static Object createExternalObject(String type) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		Object answer;

		Class<?> clazz = externalClassForName(type);
		answer = clazz.newInstance();

		return answer;
	}

}
